package com.geo.auth.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.geo.auth.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户Mapper接口
 */
@Mapper
public interface UserMapper extends BaseMapper<User> {
    
    /**
     * 根据用户名查询用户
     */
    @Select("SELECT * FROM users WHERE username = #{username} AND deleted = 0")
    User findByUsername(@Param("username") String username);
    
    /**
     * 根据邮箱查询用户
     */
    @Select("SELECT * FROM users WHERE email = #{email} AND deleted = 0")
    User findByEmail(@Param("email") String email);
    
    /**
     * 根据用户名或邮箱查询用户
     */
    @Select("SELECT * FROM users WHERE (username = #{loginName} OR email = #{loginName}) AND deleted = 0")
    User findByUsernameOrEmail(@Param("loginName") String loginName);
    
    /**
     * 更新最后登录时间
     */
    @Update("UPDATE users SET last_login_at = #{lastLoginAt}, last_login_ip = #{lastLoginIp} WHERE id = #{userId}")
    int updateLastLogin(@Param("userId") String userId, 
                       @Param("lastLoginAt") LocalDateTime lastLoginAt, 
                       @Param("lastLoginIp") String lastLoginIp);
    
    /**
     * 更新用户状态
     */
    @Update("UPDATE users SET status = #{status}, updated_at = NOW() WHERE id = #{userId}")
    int updateStatus(@Param("userId") String userId, @Param("status") String status);
    
    /**
     * 根据状态查询用户列表
     */
    @Select("SELECT * FROM users WHERE status = #{status} AND deleted = 0")
    List<User> findByStatus(@Param("status") String status);
    
    /**
     * 根据创建时间范围查询用户
     */
    @Select("SELECT * FROM users WHERE created_at >= #{startTime} AND created_at <= #{endTime} AND deleted = 0")
    List<User> findByCreateTimeRange(@Param("startTime") LocalDateTime startTime, 
                                    @Param("endTime") LocalDateTime endTime);
    
    /**
     * 检查用户名是否存在
     */
    @Select("SELECT COUNT(*) FROM users WHERE username = #{username} AND deleted = 0")
    int countByUsername(@Param("username") String username);
    
    /**
     * 检查邮箱是否存在
     */
    @Select("SELECT COUNT(*) FROM users WHERE email = #{email} AND deleted = 0")
    int countByEmail(@Param("email") String email);
    
    /**
     * 兼容性方法 - 根据用户名查询用户
     */
    default User selectByUsername(String username) {
        return findByUsername(username);
    }
    
    /**
     * 兼容性方法 - 根据邮箱查询用户
     */
    default User selectByEmail(String email) {
        return findByEmail(email);
    }
}